package com.jams.goodox.activity.mine.ox;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.jams.goodox.BasePayActivity;
import com.jams.goodox.BuildConfig;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.TownApplicationLike;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/5/27.
 */

public class OXInActi extends BasePayActivity {

    private static final String TAG = "OXInActi";
    @Bind(R.id.recycle_view)
    RecyclerView recyclerView;

    List<OxInbean> oxInbeanList;
    private  int price;
    @Override
    protected int getLayoutId() {
        return R.layout.card_cz;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this,"会员充值");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_theme));//沉侵式头部
        oxInbeanList=new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(new RecycleCommonAdapter<OxInbean>(this,oxInbeanList,R.layout.card_item) {
            @Override
            public void convert(RecycleCommonViewHolder helper, final OxInbean item, int position) {
                helper.setText(R.id.tx_bi,item.getName());
                helper.setText(R.id.tx_money,"¥ " + item.getPrice());
                helper.setOnItemClickListener(new OnRecycleItemClickListener() {
                    @Override
                    public void itemClick() {
                        price=item.getPrice();
                        createOxOrder(item.getId());
                    }
                });
            }
        });
        getDt();
        bindWXResultBroadcast();
    }

    private void getDt(){
        enqueue(createCallService(MineService.class).getOx(ProtocolManagers.getDefaultMap()), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                if (TextUtils.isEmpty(result.getResponseData())) return;
                try{
                    JsonArray jsonArray = new JsonParser().parse(result.getResponseData()).getAsJsonArray();
                    oxInbeanList.clear();
                    for(JsonElement jsonElement:jsonArray){
                        OxInbean message = new Gson().fromJson(jsonElement, OxInbean.class);
                        oxInbeanList.add(message);
                    }
                    recyclerView.getAdapter().notifyDataSetChanged();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    private void createOxOrder(String cardId){
        B b=new B();
        b.coinId=cardId;
        enqueue(createCallService(MineService.class).createOrder(ProtocolManagers.getRequestMap(b)), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                if (TextUtils.isEmpty(result.getResponseData())) return;
                Log.d(TAG,"getResponseData = " + result.getResponseData());
                try{
                    OxOrderBean oxOrderBean=new Gson().fromJson(result.getResponseData(),OxOrderBean.class);
                    if(oxOrderBean.result){
                        getWXPayInfo(new A(oxOrderBean.id,price));
                    }
                }catch (Exception e){
                    Log.d(TAG,"Exception = " + e.getMessage());
                }
            }

            @Override
            public void onError(String msg) {
                Log.d(TAG,"onError = " + msg);
            }
        });
    }

    private void getWXPayInfo(A a){

        showLoading();

        Call<ResponseBody> example = createCallService(MineService.class).getWXInfo(ProtocolManagers.getRequestMap(a));

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        String responseData = jsonObject.getString("responseData");
                        Log.d(TAG, "getWXPayInfo before responseData = " + responseData);
                        responseData = responseData.replace("\\","");
                        responseData = responseData.substring(1,responseData.length() - 1);
                        Log.d(TAG, "getWXPayInfo after responseData = " + responseData);
                        responseData = responseData.replace("\"{","{").replace("}\"","}");

                        JSONObject object = new JSONObject(responseData);

                        String orderNo = object.getString("orderNo");
                        Log.d(TAG, "orderNo  = " + orderNo);
                        JSONObject childObj = new JSONObject(object.getString("payData"));

                        String sign = childObj.getString("sign");
                        String appid = childObj.getString("appid");
                        String noncestr = childObj.getString("noncestr");
                        String packages = childObj.getString("package");
                        String partnerid = childObj.getString("partnerid");
                        String prepayid = childObj.getString("prepayid");
                        String timestamp = childObj.getString("timestamp");

                        PayReq payReq = new PayReq();
                        payReq.appId = appid;
                        payReq.nonceStr = noncestr;
                        payReq.packageValue = packages;
                        payReq.partnerId = partnerid;
                        payReq.prepayId = prepayid;
                        payReq.timeStamp = timestamp;
                        payReq.sign = sign;

                        IWXAPI msgapi = WXAPIFactory.createWXAPI(TownApplicationLike.getInstance(), null);
                        // 将该app注册到微信
//                                msgapi.registerApp(Constant.WEIXIN_APPID);
                        msgapi.registerApp(BuildConfig.WEIXIN_APPID);
                        msgapi.sendReq(payReq);

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }

    static class A{
        public A(String id,int price){
            this.memberId=SePref.getId();
            this.outOrderId=id;
            this.outOrderNo=id;
            this.payAmount=price;
        }
        int memberId;
        String subject="氧币购买";
        String outOrderId;
        String outOrderNo;
        int outOrderType=3;
        int payAmount=1;
        String device_info="android";
        String requestIp="";
    }

    static class B{
        String coinId;
        int memberId=SePref.getId();
    }
}
